﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Process.API.Application.Command.Show;
using Process.API.DTOs;
using Process.Domain;
using Process.ErrorCode;
using Process.Infrastructure.Interface;
using MaterialManagement.Domain.ERP;

namespace Process.API.Application.Handler.Show
{
    public class ShowProductionMaterialTableHandler : IRequestHandler<ShowProductionMaterialTableCommand, APIResult<List<ProductionMaterialDto>>>
    {
        private readonly IBaseRepository<ProductionMaterialTable> proRep;
        private readonly IBaseRepository<MaterialInfoModel> materialRep;

        public ShowProductionMaterialTableHandler(IBaseRepository<ProductionMaterialTable> proRep, IBaseRepository<MaterialInfoModel> materialRep)
        {
            this.proRep = proRep;
            this.materialRep = materialRep;
        }

        public async Task<APIResult<List<ProductionMaterialDto>>> Handle(ShowProductionMaterialTableCommand request, CancellationToken cancellationToken)
        {
            var query =
                from pmt in proRep.GetAll().Where(x => !x.IsDel)
                join mim in materialRep.GetAll().Where(x => !x.IsDel) on pmt.MaterialCode equals mim.MaterialCode into gj
                from mim in gj.DefaultIfEmpty()
                where pmt.ProductionOrdersId == request.ProductionOrdersId
                select new ProductionMaterialDto
                {
                    ProductionMaterialId = pmt.ProductionMaterialId,
                    ProductionOrdersId = pmt.ProductionOrdersId,
                    MaterialCode = pmt.MaterialCode,
                    MaterialName = mim == null ? string.Empty : mim.MaterialName,
                    Unit = mim == null ? string.Empty : mim.Unit,
                    Specification = mim == null ? string.Empty : mim.Specification,
                    Attribute = mim == null ? false : mim.Attribute,
                    Inventorylimit = mim == null ? 0 : mim.Inventorylimit,
                    Inventorylevel = mim == null ? 0 : mim.Inventorylevel,
                    CurrentInventory = mim == null ? 0 : mim.CurrentInventory,
                    WarehouseCode = mim == null ? string.Empty : mim.WarehouseCode,
                    PurchasePrice = mim == null ? 0 : mim.PurchasePrice,
                    PeriodOfValidity = mim == null ? 0 : mim.PeriodOfValidity,
                    MaterialState = mim == null ? false : mim.MaterialState,
                    IsDel = pmt.IsDel
                };

            var list = await query.ToListAsync(cancellationToken);

            return new APIResult<List<ProductionMaterialDto>>
            {
                Code = APIEnum.Ok,
                Message = "生产工单物料清单查询成功",
                Data = list
            };
        }
    }
}
